package org.springblade.modules.huikecloud.utils;

import org.springblade.common.constant.CommonConstant;

import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;

public class ScriptUtil {




    /**
     * 运行shell脚本
     *
     * @param shell 需要运行的shell脚本
     */
    public static void execShell(String shell) {
        try {
            Runtime.getRuntime().exec(shell);
            System.out.println("脚本执行成功");
        } catch (Exception e) {
            System.out.println("脚本执行失败");
            e.printStackTrace();
        }
    }

    /**
     * 运行shell脚本 new String[]方式
     *
     * @param shell 需要运行的shell脚本
     */
    public static boolean execShellBin(String shell, String msg) {
        try {
            System.out.println(shell);
            Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", shell}, null, null);
            System.out.println(msg + "执行成功");
            return true;
        } catch (Exception e) {
            System.out.println(msg + "执行失败");
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 运行shell并获得结果，注意：如果sh中含有awk,一定要按new String[]{"/bin/sh","-c",shStr}写,才可以获得流
     *
     * @param shell 需要执行的shell
     * @return
     */
    public static boolean runShell(String shell, String msg) {
        List<String> strList = new ArrayList<String>();
        try {
            System.out.println(shell);
            if (CommonConstant.CLOUD_EXEC){
                Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", shell}, null, null);
                InputStreamReader ir = new InputStreamReader(process.getInputStream());
                LineNumberReader input = new LineNumberReader(ir);
                String line;
                process.waitFor();
                while ((line = input.readLine()) != null) {
                    strList.add(line);
                }
                //            得到脚本运行成功与否的标志 ：0－成功 非0－失败
                int i = process.exitValue();
                System.out.println(strList.toString());
                if (i==0){
                    System.out.println(msg + "执行成功");
                    return true;
                }
            }

            return false;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(msg + "执行失败");
        }
        System.out.println(strList.toString());
        return false;
    }
}
